package com.cxl.demo.awareness;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hms.kit.awareness.Awareness;
import com.huawei.hms.kit.awareness.barrier.AwarenessBarrier;
import com.huawei.hms.kit.awareness.barrier.BarrierStatus;
import com.huawei.hms.kit.awareness.barrier.TimeBarrier;
import com.huawei.hms.kit.awareness.capture.WeatherStatusResponse;
import com.huawei.hms.kit.awareness.status.WeatherStatus;
import com.huawei.hms.kit.awareness.status.weather.City;
import com.huawei.hms.kit.awareness.status.weather.Situation;
import com.huawei.hms.kit.awareness.status.weather.WeatherSituation;
import com.huawei.hms.kit.awareness.status.weather.constant.CNWeatherId;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {
    private static final String WEATHER_REMIND_BARRIER_LABEL = "weather remind barrier label";
    private static final String ORDER_FOOD_REMIND_BARRIER_LABEL = "order food remind barrier label";

    private static final int PERMISSION_REQUEST_CODE = 0x100;
    //权限列表
    private final String[] mPermissionsList = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};

    private SwitchCompat weather_remind_switch;
    private SwitchCompat order_food_remind_switch;
    private TextView msg_tv;

    private PendingIntent mPendingIntent;
    private TimeBarrierReceiver mBarrierReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        weather_remind_switch = findViewById(R.id.weather_remind_switch);
        order_food_remind_switch = findViewById(R.id.order_food_remind_switch);
        msg_tv = findViewById(R.id.msg_tv);
        weather_remind_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    addWeatherRemind();
                } else {
                    BarrierUtils.deleteBarrier(MainActivity.this, new BarrierCallback() {
                        @Override
                        public void onSuccess() {
                            showToast("关闭提醒成功");
                        }

                        @Override
                        public void onFailure() {
                            showToast("关闭提醒失败");
                        }
                    }, WEATHER_REMIND_BARRIER_LABEL);
                }
            }
        });
        order_food_remind_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    addOrderFoodRemind();
                } else {
                    BarrierUtils.deleteBarrier(MainActivity.this, new BarrierCallback() {
                        @Override
                        public void onSuccess() {
                            showToast("关闭提醒成功");
                        }

                        @Override
                        public void onFailure() {
                            showToast("关闭提醒失败");
                        }
                    }, ORDER_FOOD_REMIND_BARRIER_LABEL);
                }
            }
        });

        //创建PendingIntent
        final String barrierReceiverAction = getApplication().getPackageName() + "TIME_BARRIER_RECEIVER_ACTION";
        Intent intent = new Intent(barrierReceiverAction);
        mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //注册广播接收器
        mBarrierReceiver = new TimeBarrierReceiver();
        registerReceiver(mBarrierReceiver, new IntentFilter(barrierReceiverAction));

        //请求权限
        requestPermissions();
    }

    /**
     * 添加天气提醒围栏
     */
    private void addWeatherRemind() {
        long oneHourMilliSecond = 60 * 60 * 1000L;
        //工作日围栏
        AwarenessBarrier weekdayBarrier = TimeBarrier.inTimeCategory(TimeBarrier.TIME_CATEGORY_WEEKDAY);
        //时间围栏,7点到8点
        AwarenessBarrier periodOfDayBarrier = TimeBarrier.duringPeriodOfDay(TimeZone.getDefault(),
                7 * oneHourMilliSecond, 8 * oneHourMilliSecond);
        //组合围栏
        AwarenessBarrier weatherRemindBarrier = AwarenessBarrier.and(weekdayBarrier, periodOfDayBarrier);
        BarrierUtils.addBarrier(this, WEATHER_REMIND_BARRIER_LABEL, weatherRemindBarrier,
                mPendingIntent, new BarrierCallback() {
                    @Override
                    public void onSuccess() {
                        showToast("打开提醒成功");
                    }

                    @Override
                    public void onFailure() {
                        showToast("打开提醒失败");
                    }
                });
    }

    /**
     * 添加点餐提醒围栏
     */
    private void addOrderFoodRemind() {
        long oneHourMilliSecond = 60 * 60 * 1000L;
        //工作日围栏
        AwarenessBarrier weekdayBarrier = TimeBarrier.inTimeCategory(TimeBarrier.TIME_CATEGORY_WEEKDAY);
        //时间围栏,10:30点到11点
        AwarenessBarrier periodOfDayBarrier = TimeBarrier.duringPeriodOfDay(TimeZone.getDefault(),
                10 * oneHourMilliSecond + 30 * 60 * 1000L, 11 * oneHourMilliSecond);
        //组合围栏
        AwarenessBarrier orderFoodRemindBarrier = AwarenessBarrier.and(weekdayBarrier, periodOfDayBarrier);
        BarrierUtils.addBarrier(this, ORDER_FOOD_REMIND_BARRIER_LABEL, orderFoodRemindBarrier,
                mPendingIntent, new BarrierCallback() {
                    @Override
                    public void onSuccess() {
                        showToast("打开提醒成功");
                    }

                    @Override
                    public void onFailure() {
                        showToast("打开提醒失败");
                    }
                });
    }

    /**
     * 是否需要带伞
     *
     * @return
     */
    private boolean needUmbrella(int cnWeatherId) {
        //CNWeatherId.SUNNY 晴，CNWeatherId.CLOUDY 多云,CNWeatherId.OVERCAST 阴...后面基本上都不是好天气
        //所以这边除了晴和多云，其他都带伞吧
        if (cnWeatherId > CNWeatherId.CLOUDY) {
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBarrierReceiver != null) {
            unregisterReceiver(mBarrierReceiver);
        }
    }

    /**
     * 请求权限
     */
    private void requestPermissions() {
        List<String> permissionsDoNotGrant = new ArrayList<>();
        for (String permission : mPermissionsList) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsDoNotGrant.add(permission);
            }
        }
        if (permissionsDoNotGrant.size() > 0) {
            ActivityCompat.requestPermissions(this, permissionsDoNotGrant.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean hasPermissionDenied = false;
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    hasPermissionDenied = true;
                }
            }
            if (hasPermissionDenied) {
                showToast("获取权限失败");
            }
        }
    }

    final class TimeBarrierReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            BarrierStatus barrierStatus = BarrierStatus.extract(intent);
            String label = barrierStatus.getBarrierLabel();
            int barrierPresentStatus = barrierStatus.getPresentStatus();
            switch (label) {
                case WEATHER_REMIND_BARRIER_LABEL:
                    Log.d("tag001", "weather remind barrierPresentStatus:" + barrierPresentStatus);
                    if (barrierPresentStatus == BarrierStatus.TRUE) {
                        //获取天气情况
                        Awareness.getCaptureClient(MainActivity.this).getWeatherByDevice()
                                // 执行成功的回调监听
                                .addOnSuccessListener(new OnSuccessListener<WeatherStatusResponse>() {
                                    @Override
                                    public void onSuccess(WeatherStatusResponse weatherStatusResponse) {
                                        try {
                                            WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
                                            WeatherSituation weatherSituation = weatherStatus.getWeatherSituation();
                                            Situation situation = weatherSituation.getSituation();
                                            City city = weatherSituation.getCity();
                                            //天气，0表示晴，1表示多云，7表示小雨等
                                            int cnWeatherId = situation.getCnWeatherId();
                                            //是否需要带伞
                                            boolean needUmbrella = needUmbrella(cnWeatherId);
                                            //温度
                                            long temperatureC = situation.getTemperatureC();
                                            StringBuilder stringBuilder = new StringBuilder();
                                            stringBuilder.append(city.getName());
                                            if (cnWeatherId == CNWeatherId.SUNNY) {
                                                stringBuilder.append("今天晴天,");
                                            } else if (cnWeatherId == CNWeatherId.CLOUDY) {
                                                stringBuilder.append("今天多云,");
                                            } else {
                                                stringBuilder.append("今天天气不太好，记得带伞,");
                                            }
                                            stringBuilder.append("温度" + temperatureC + "℃");
                                            if (temperatureC < 10) {
                                                stringBuilder.append(",注意保暖。");
                                            } else {
                                                stringBuilder.append("。");
                                            }
                                            showMsg(stringBuilder.toString());
                                            showNotification("天气提醒", stringBuilder.toString());
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            showToast("获取天气失败");
                                        }
                                    }
                                })
                                // 执行失败的回调监听
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(Exception e) {
                                        e.printStackTrace();
                                        showToast("获取天气失败");
                                    }
                                });
                    }
                    break;
                case ORDER_FOOD_REMIND_BARRIER_LABEL:
                    Log.d("tag001", "order food remind barrierPresentStatus:" + barrierPresentStatus);
                    if (barrierPresentStatus == BarrierStatus.TRUE) {
                        showMsg("该点餐了,要不然没饭吃啦^-^");
                        showNotification("点餐提醒", "该点餐了,要不然没饭吃啦^-^");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void showMsg(String msg) {
        msg_tv.setText(msg);
    }

    /**
     * 通知栏显示通知
     *
     * @param title
     * @param msg
     */
    private void showNotification(String title, String msg) {
        Notification notification;
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "MainActivity";
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "MainActivity", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(this)
                    .setChannelId(CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentIntent(resultPendingIntent)
                    .setContentText(msg)
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            Notification.Builder builder = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(title)
                    .setContentText(msg)
                    .setDefaults(Notification.DEFAULT_ALL);
            notification = builder.build();
            builder.setContentIntent(resultPendingIntent);
        }
        notificationManager.notify(1, notification);

    }
}